<!DOCTYPE html>
<html>
<head>
    <title>Ball Collision</title>
    <style>
        canvas {
            border: 1px solid black;
        }
        #game-container {
            display: flex;
            flex-direction: column;
            align-items: center;
        }
        #score-container {
            margin-top: 10px;
            font-size: 20px;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <div id="game-container">
        <canvas id="myCanvas" width="400" height="400"></canvas>
        <div id="score-container">Score: 0</div>
    </div>
    <script>
        // 获取canvas元素
        const canvas = document.getElementById('myCanvas');
        const ctx = canvas.getContext('2d');
        const scoreContainer = document.getElementById('score-container');

        // 游戏状态
        let score = 0;
        let gameOver = false;


        // 球的属性
        const balls = [];
        const ballsToRemove = []; // 存储需要删除的球体索引


        balls.push({
                x: Math.random() * (canvas.width - 40) + 20,
                y: Math.random() * (canvas.height - 40) + 20,
                radius: 20,
                color: 'red',
                speedX: Math.random() * 6 - 3,
                speedY: Math.random() * 6 - 3
        });


        // 初始化小球数量和位置
        const numBalls = 5; // 设置小球数量
        for (let i = 0; i < numBalls; i++) {
            const isRed = Math.random() < 0.2; // 20% 的概率为红色球体
            balls.push({
                x: Math.random() * (canvas.width - 40) + 20,
                y: Math.random() * (canvas.height - 40) + 20,
                radius: 20,
                color: `rgb(${Math.floor(Math.random() * 256)}, ${Math.floor(Math.random() * 256)}, ${Math.floor(Math.random() * 256)})`,
                speedX: Math.random() * 6 - 3,
                speedY: Math.random() * 6 - 3
            });
        }

        // 绘制球
        function drawBalls() {
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            balls.forEach((ball, index) => {
                if (!ballsToRemove.includes(index)) { // 只绘制未被删除的球体
                    ctx.beginPath();
                    ctx.arc(ball.x, ball.y, ball.radius, 0, Math.PI * 2);
                    ctx.fillStyle = ball.color;
                    ctx.fill();
                    ctx.closePath();
                }
            });
        }

        // 更新球的位置
        function moveBalls() {
            balls.forEach((ball, index) => {
                if(balls.length == 1){
                    endGame();
                }


                if (!ballsToRemove.includes(index)) { // 只更新未被删除的球体
                    ball.x += ball.speedX;
                    ball.y += ball.speedY;

                    // 检测碰撞
                    if (ball.x + ball.radius > canvas.width || ball.x - ball.radius < 0) {
                        ball.speedX = -ball.speedX;
                    }
                    if (ball.y + ball.radius > canvas.height || ball.y - ball.radius < 0) {
                        ball.speedY = -ball.speedY;
                    }

                    // 检测球与球之间的碰撞
                    balls.forEach((otherBall, otherIndex) => {
                        if (!ballsToRemove.includes(otherIndex) && otherBall !== ball) {
                            const dx = ball.x - otherBall.x;
                            const dy = ball.y - otherBall.y;
                            const distance = Math.sqrt(dx * dx + dy * dy);
                            if (distance < ball.radius + otherBall.radius) {
                                // 发生碰撞,交换速度
                                const tempSpeedX = ball.speedX;
                                const tempSpeedY = ball.speedY;
                                ball.speedX = otherBall.speedX;
                                ball.speedY = otherBall.speedY;
                                otherBall.speedX = tempSpeedX;
                                otherBall.speedY = tempSpeedY;

                                // 如果碰撞的球体是红色球体,则将需要删除的球体索引添加到数组中
                                if (otherBall.color === 'red') {
                                    score += 10;
                                    updateScoreDisplay();
                                    ballsToRemove.push(index);
                                } else if (ball.color === 'red') {
                                    score += 10;
                                    updateScoreDisplay();
                                    ballsToRemove.push(otherIndex);
                                }
                            }
                        }
                    });
                }
            });
        }

        // 更新分数显示
        function updateScoreDisplay() {
            scoreContainer.textContent = `Score: ${score}`;
        }
        

        // 游戏结束
        function endGame() {
            gameOver = true;
            for (let i = 0; i < numBalls; i++) {
            const isRed = Math.random() < 0.2; // 20% 的概率为红色球体
            balls.push({
                x: Math.random() * (canvas.width - 40) + 20,
                y: Math.random() * (canvas.height - 40) + 20,
                radius: 20,
                color: `rgb(${Math.floor(Math.random() * 256)}, ${Math.floor(Math.random() * 256)}, ${Math.floor(Math.random() * 256)})`,
                speedX: Math.random() * 6 - 3,
                speedY: Math.random() * 6 - 3
            });
        }
            // alert(`Game Over! Your score is ${score}`);
        }

        // 动画循环
        function animate() {
            moveBalls();
            drawBalls();

            // 删除需要删除的球体
            ballsToRemove.forEach(index => {
                balls.splice(index, 1);
            });
            ballsToRemove.length = 0; // 清空需要删除的球体数组

            requestAnimationFrame(animate);
        }

        animate();
    </script>
</body>
</html>